package com.haitaoit.chengquan.module.home.activity.forum;

import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BackCall;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.module.home.activity.SearchActivity;
import com.haitaoit.chengquan.module.home.adapter.forum.ForumCenterAdapter;
import com.haitaoit.chengquan.module.home.adapter.forum.ForumDownAdapter;
import com.haitaoit.chengquan.module.home.model.ForumCenterModel;
import com.haitaoit.chengquan.module.home.model.TitleModel;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.DateTimeUtil;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.view.MyGridView;
import com.haitaoit.chengquan.view.MyListView;
import com.haitaoit.chengquan.view.PullToRefreshBase;
import com.haitaoit.chengquan.view.PullToRefreshScrollView;
import com.haitaoit.chengquan.view.SyncHorizontalScrollView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class ForumCenterActivity extends BaseActivity implements PullToRefreshBase.OnRefreshListener<ScrollView> {
    @ViewInject(R.id.mHsv)
    SyncHorizontalScrollView mHsv;
    @ViewInject(R.id.rg_nav_content)
    RadioGroup               rg_nav_content;
    @ViewInject(R.id.down_more)
    ImageView                down_more;
    @ViewInject(R.id.pull_to_refresh_scrollview)

    PullToRefreshScrollView  pullrefreshscrollview;
    private LinearLayout null_information_layout;
    private MyListView   listView;
    private ScrollView   mScrollView;

    private boolean isFrist = true;
    private int     page    = 1;
    private ToastUtils         toast;
    private ForumCenterAdapter adapter;

    private PopupWindow myPopWindow;
    private List<TitleModel> titleList            = new ArrayList<TitleModel>();
    private int              currentIndicatorLeft = 0;// 下标
    private int              SelectIndex          = 0, type = 1;
    private String SelectId = "0", search_title = "";

    //记录当前横向的rediubutton的选项
    private String select = "";
    private View mIamgeOne;
    private View mIamgeTwo;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forum_center);
        ViewUtils.inject(this);


        View view = LayoutInflater.from(this).inflate(R.layout.scrollview_listview_layout, null);
        mIamgeOne = findViewById(R.id.new_text);
        mIamgeTwo = findViewById(R.id.getyou_text);
        mIamgeTwo.setVisibility(View.INVISIBLE);
        mIamgeOne.setVisibility(View.VISIBLE);


        null_information_layout = (LinearLayout) view.findViewById(R.id.null_information_layout);
        listView = (MyListView) view.findViewById(R.id.scrollview_listview);

        pullrefreshscrollview.setPullLoadEnabled(true);
        pullrefreshscrollview.setPullRefreshEnabled(true);
        pullrefreshscrollview.setOnRefreshListener(this);
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        mScrollView = pullrefreshscrollview.getRefreshableView();
        mScrollView.setFillViewport(true);
        mScrollView.setVerticalScrollBarEnabled(false);
        mScrollView.addView(view);

        adapter = new ForumCenterAdapter(this);
        adapter.setBackCall(backCall);
        listView.setAdapter(adapter);


        select = "";
        httpGetesther_class_list();
    }

    @Override
    protected void onResume() {
        super.onResume();
        pullrefreshscrollview.onPullDownRefreshComplete();
        httpGetesther_class_list();
    }

    // 搜索返回刷新
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 21 && resultCode == 1) {
            search_title = data.getStringExtra("search_title");
            isFrist = true;
            page = 1;
            httpGetesther_list();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @OnClick({R.id.left, R.id.search, R.id.send_forum, R.id.forum_center_new,
            R.id.forum_center_send, R.id.down_more,})
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.left:
                finish();
                break;
            case R.id.search:// 搜索
                intent.setClass(this, SearchActivity.class);
                intent.putExtra("type", "forum");
                intent.putExtra("search_title", search_title);
                startActivityForResult(intent, 21);
                break;
            case R.id.send_forum:// 发送帖子
                //TODO：传送到对应的类，进行对应的发帖操作

                //                PreferenceUtils.setPrefString(ForumCenterActivity.this, "text_name", select);
                //这里的intent传递不过去，因此保存本地进行读取
                intent.putExtra("text_name", select);
                //查看当前选择的条目
                intent.setClass(this, QPostForumActivity.class);
                //                intent.setClass(this, PostForumActivity.class);
                //                startActivityForResult(intent, 20);

                startActivity(intent);
                break;
            case R.id.forum_center_new:// 最新发布
                type = 1;
                isFrist = true;
                page = 1;
                mIamgeTwo.setVisibility(View.INVISIBLE);
                mIamgeOne.setVisibility(View.VISIBLE);
                httpGetesther_list();
                break;
            case R.id.forum_center_send:// 最新推荐
                type = 2;
                isFrist = true;
                page = 1;
                mIamgeTwo.setVisibility(View.VISIBLE);
                mIamgeOne.setVisibility(View.INVISIBLE);
                httpGetesther_list();
                break;
            case R.id.down_more:// 类别下拉
                iniPopupWindow();
                down_more.setImageResource(R.mipmap.down_1);
                myPopWindow.showAsDropDown(mHsv, 0, 0);
                break;
        }
        super.onClick(v);
    }

    BackCall backCall = new BackCall() {
        @Override
        public void deal(int which, Object... obj) {
            int position = (Integer) obj[0];
            switch (which) {
                case R.id.forum_itemll:

                    Intent intent = new Intent(ForumCenterActivity.this, ForumDetailActivity.class);
                    intent.putExtra("id", adapter.getList().get(position).getId());
                    startActivity(intent);
                    break;
            }
            super.deal(which, obj);
        }
    };

    private void httpGetesther_list() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("type", type + ""));
        list.add(new NameValuePairSign("esther_class_id", SelectId));
        list.add(new NameValuePairSign("title", search_title));
        list.add(new NameValuePairSign("page", page + ""));
        list.add(new NameValuePairSign("pagesize", Constant.PageSize));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("type", type + "");
        params.addQueryStringParameter("esther_class_id", SelectId);
        params.addQueryStringParameter("title", search_title);
        params.addQueryStringParameter("page", page + "");
        params.addQueryStringParameter("pagesize", Constant.PageSize);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getesther_list, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String result = arg0.result.toString();
                List<ForumCenterModel> new_list = new ArrayList<ForumCenterModel>();
                try {
                    JSONObject json = new JSONObject(result);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            pullrefreshscrollview.onPullDownRefreshComplete();
                            pullrefreshscrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<ForumCenterModel>();
                            hideProgree();
                            break;
                        case 0:// 成功
                            new_list = gson.fromJson(Response,
                                    new TypeToken<List<ForumCenterModel>>() {
                                    }.getType());
                            hideProgree();

                            break;
                        case 2:// 暂无内容
                            pullrefreshscrollview.onPullDownRefreshComplete();
                            pullrefreshscrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<ForumCenterModel>();
                            hideProgree();
                            break;
                    }
                    if (isFrist) {
                        if (isNullDate(new_list)) {
                            adapter.setList(new_list);
                            adapter.notifyDataSetChanged();
                        }
                        pullrefreshscrollview.onPullDownRefreshComplete();
                    } else {
                        List<ForumCenterModel> allList = adapter.getList();
                        allList.addAll(new_list);
                        adapter.setList(allList);
                        adapter.notifyDataSetChanged();
                        pullrefreshscrollview.onPullUpRefreshComplete();
                    }

                    hideProgree();
                } catch (JSONException e) {
                    e.printStackTrace();
                    hideProgree();
                }
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
                hideProgree();

            }
        });
    }

    private void httpGetesther_class_list() {
        int i = (int) Math.floor(Math.random() * 9000 + 1000);
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("rnd", i + ""));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("rnd", i + "");
        params.addQueryStringParameter("sign", sign);
        showProgrees("");
        HttpUtilsSingle.doGet(this, false, Constant.Getesther_class_list, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            hideProgree();
                            return;
                        case 0:// 成功
                            List<TitleModel> list = gson.fromJson(Response,
                                    new TypeToken<List<TitleModel>>() {
                                    }.getType());
                            if (titleList.size()!=1){
                                titleList.clear();
                            }
                            titleList.add(new TitleModel("0", "全部"));
                            for (int i = 0; i < list.size(); i++) {
                                titleList.add(list.get(i));
                            }
                            initNavigationHSV(titleList.size());
                            //TODO:监听点击的具体哪个键
                            setListener();
                            httpGetesther_list();
                            hideProgree();
                            return;
                        case 2:// 暂无内容
                            ToastUtils.showToast(Errmsg);
                            hideProgree();
                            return;
                    }

                    hideProgree();
                } catch (JSONException e) {
                    e.printStackTrace();
                    hideProgree();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
                httpGetesther_list();
                hideProgree();
            }
        });
    }

    // 弹出框
    private void iniPopupWindow() {

        View layout = LayoutInflater.from(this).inflate(R.layout.forum_down_item, null);
        layout.findViewById(R.id.forum_dismiss).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myPopWindow.dismiss();

            }
        });
        MyGridView forum_dwom_grid = (MyGridView) layout.findViewById(R.id.forum_dwom_grid);
        final ForumDownAdapter fdAdapter = new ForumDownAdapter(this);
        fdAdapter.setIsIndex(SelectIndex);
        fdAdapter.setList(titleList);
        fdAdapter.setBackCall(new BackCall() {
            @Override
            public void deal(int which, Object... obj) {
                int position = (Integer) obj[0];
                switch (which) {
                    case R.id.text:
                        SelectIndex = position;
                        SelectId = fdAdapter.getList().get(position).getId();
                        fdAdapter.setIsIndex(SelectIndex);
                        fdAdapter.notifyDataSetChanged();
                        ((RadioButton) rg_nav_content.getChildAt(SelectIndex)).setTextColor(getResources().getColor(R.color.app_color));
                        ((RadioButton) rg_nav_content.getChildAt(SelectIndex)).setChecked(true);
                        break;
                }
                myPopWindow.dismiss();
                super.deal(which, obj);
            }
        });

        if (titleList.size() >= 3) {
            forum_dwom_grid.setNumColumns(3);
            for (int i = 0; i < titleList.size(); i++) {
                if (titleList.get(i).getName().length() >= 6) {
                    forum_dwom_grid.setNumColumns(3);
                    break;
                }
            }
        }
        forum_dwom_grid.setAdapter(fdAdapter);

        myPopWindow = new PopupWindow(layout);
        myPopWindow.setFocusable(true); // 加上这个popupwindow中的ListView才可以接收点击事件
        // 控制popupwindow 的宽度和高度
        myPopWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        myPopWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);

        // 控制popupwindow 点击屏幕其他地方消失
        myPopWindow.setBackgroundDrawable(this.getResources().getDrawable(R.color.transparent)); // 设置背景图片,不能在布局中设置，要通过代码来设置
        myPopWindow.setOutsideTouchable(true);
        // 触摸popupwindow外部,popupwindow消失,这个要求你的popupwindow要有背景图片才可以成功
        myPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                down_more.setImageResource(R.mipmap.down);;
            }
        });
    }

    private void initNavigationHSV(int size) {
        if (size >= 4) {
            size = 4;
            for (int i = 0; i < titleList.size(); i++) {
                if (titleList.get(i).getName().length() >= 6) {
                    size = 3;
                    break;
                }
            }
        }
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int indicatorWidth = dm.widthPixels / size;
        LayoutInflater mInflater = LayoutInflater.from(this);

        rg_nav_content.removeAllViews();

        for (int i = 0; i < titleList.size(); i++) {
            RadioButton rb = (RadioButton) mInflater.inflate(R.layout.forum_type_item, null);
            // rb.setId(Integer.valueOf(list.get(i).getCategory_id()));

            rb.setId(i);
            rb.setText(titleList.get(i).getName());
            rb.setTextColor(getResources().getColor(R.color.text_gray));
            rb.setLayoutParams(new LinearLayout.LayoutParams(indicatorWidth, LinearLayout.LayoutParams.MATCH_PARENT));
            rg_nav_content.addView(rb);
        }
        ((RadioButton) rg_nav_content.getChildAt(0)).setTextColor(getResources().getColor(R.color.app_color));
        ((RadioButton) rg_nav_content.getChildAt(0)).setChecked(true);
    }

    private void setListener() {
        rg_nav_content.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (rg_nav_content.getChildAt(checkedId) != null) {
                    TranslateAnimation animation = new TranslateAnimation(currentIndicatorLeft,
                            ((RadioButton) rg_nav_content.getChildAt(checkedId)).getLeft(), 0f, 0f);
                    animation.setInterpolator(new LinearInterpolator());
                    animation.setDuration(100);
                    animation.setFillAfter(true);

                    // 执行位移动画
                    for (int i = 0; i < titleList.size(); i++) {
                        RadioButton ra_but = (RadioButton) rg_nav_content.getChildAt(i);
                        ra_but.setTextColor(getResources().getColor(R.color.black_text));
                        if (i == checkedId) {
                            SelectIndex = i;
                            SelectId = titleList.get(i).getId();
                            isFrist = true;
                            page = 1;
                            httpGetesther_list();
                            RadioButton ra_but2 = (RadioButton) rg_nav_content.getChildAt(i);
                            ra_but2.setTextColor(getResources().getColor(R.color.app_color));
                        }
                    }
                    // 记录当前下标的距最左侧的 距离
                    currentIndicatorLeft = ((RadioButton) rg_nav_content.getChildAt(checkedId)).getLeft();
                    mHsv.smoothScrollTo((checkedId > 1 ? ((RadioButton) rg_nav_content.getChildAt(checkedId)).getLeft() : 0)
                            - ((RadioButton) rg_nav_content.getChildAt(1)).getLeft(), 0);

                    //TODO:这里进行点击时进行赋值
                    select = titleList.get(checkedId).getName();

                }
            }
        });
    }

    /**
     * @tab 判断listview是否有值
     */
    private boolean isNullDate(List<ForumCenterModel> rewordList) {
        if (rewordList == null || rewordList.size() == 0) {
            null_information_layout.setVisibility(View.VISIBLE);
            listView.setVisibility(View.GONE);
            return false;
        } else {
            null_information_layout.setVisibility(View.GONE);
            listView.setVisibility(View.VISIBLE);
            return true;
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        search_title = "";
        isFrist = true;
        page = 1;
        httpGetesther_list();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        isFrist = false;
        page++;
        httpGetesther_list();
    }
}
